<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2022-08-30 14:17:45
 * @LastEditors: 李天惊 uf_lee@163.com
 * @LastEditTime: 2022-09-02 10:32:50
 * @FilePath: \ahbs\uc_sys\src\views\UserCenter\SysRole\components\AppSet.vue
 * Copyright (c) 2022 by 李天惊 uf_lee@163.com, All Rights Reserved. 
-->
<script setup lang="ts">
import { ref, reactive, PropType, watch } from 'vue'
import { ElCheckbox } from 'element-plus'
import { changeApp } from '@/utils/lee'
import { ucAppListApi } from '@/api/uc/app'
import { ucRoleAppSeeApi } from '@/api/uc/roleApp'
// 定义一些常用数据
const data = reactive<any>({
  appData: [],
  myRoleApp: [], //当前角色的权限
  form: {},
  newAppData: []
})
//首先拿到行数据
const props = defineProps({
  formData: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  }
})
const newFormData = ref<any>({})
watch(
  () => props.formData,
  (value) => {
    if (!value) return
    newFormData.value = value
  },
  {
    deep: true,
    immediate: true
  }
)
//获取所有app数据
const getAllApp = async () => {
  let res = await ucAppListApi({})
    .catch(() => {})
    .finally(() => {})
  if (res) {
    data.appData = res.data
  }
}

const getMyRoleApp = async () => {
  let res = await ucRoleAppSeeApi({ role_id: newFormData.value.role_id })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    data.myRoleApp = res.data
    res.data.forEach((item) => {
      if (item.authority == 1) {
        data.form[item.app_id] = true
      }
    })
  }
}

const getParentRoleApp = async () => {
  let res = await ucRoleAppSeeApi({ role_id: newFormData.value.parent_id })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    data.ParentRoleApp = res.data
  }
}

const getIds = () => {
  let ids: any = []
  for (let key in data.form) {
    if (data.form[key] == true) {
      ids.push(key)
    }
  }
  return ids
}

defineExpose({
  getCheckedKeys() {
    return getIds()
  },
  oldFormData: props.formData
})

// 初始化
const init = async () => {
  // 获取所有应用权限
  await getAllApp()
  if (newFormData.value.parent_id != 0) {
    // 获取上级角色的应用权限
    await getParentRoleApp()
    // let newAppData: any = []
    // data.ParentRoleApp.forEach((item) => {
    //   if (item.authority == 1) {
    //     newAppData.push(
    //       data.appData.find((item2) => {
    //         return item2.app_id == item.app_id
    //       })
    //     )
    //   }
    // })
    data.newAppData = changeApp(data.appData, data.ParentRoleApp)
  } else {
    // 没有上级角色就可以设置全部应用
    data.newAppData = data.appData
  }
  // 查看当前角色的应用权限
  await getMyRoleApp()
}
init()
</script>

<template>
  <div>
    <ElCheckbox
      v-for="(item, index) in data.newAppData"
      :key="index"
      :label="item.app_name"
      v-model="data.form[item.app_id]"
    />
    <div v-if="data.newAppData.length == 0"> 没有数据 </div>
  </div>
</template>
